package BluetoothFileMgr.start;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import android.os.Handler;
import android.widget.TextView;

public class LANServer extends Thread{

	Socket client;
	public ServerSocket server;
	//public String SERVERIP="";
	private Handler handler = new Handler();
	private TextView tv=null;
	
	public LANServer(TextView tv)
	{
		this.tv=tv;
		//SERVERIP=getLocalIpAddress();
		//tv.append("Server IP : "+SERVERIP);
		try{
			
		}
		catch(Exception e)
		{
			
		}
	}
	
	public void post(final String s)
	{
		handler.post(new Runnable() {
            public void run() {
                tv.append("\n"+s);
            }
        });
	}
	
	public void run() {
		post("Waiting for a Connection...");
        try {          
        	server = new ServerSocket(1258);
                // listen for incoming clients
                client = server.accept();
                post("Connected");
                handler.post(new Runnable() {
                    public void run() {
                    	try{
                    	DataInputStream in=new DataInputStream(client.getInputStream());
                        DataOutputStream out=new DataOutputStream(client.getOutputStream());
                        Thread t=new ServerMgr(in,out,tv);
                        t.start();
                    	}
                    	catch(Exception e)
                    	{
                    		post(e.getMessage());
                    	}
                    }
                });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
	
	/*private String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
                }
            }
        } catch (SocketException ex) {
            tv.append(ex.getMessage());
        }
        return null;
    }*/
}
